<?php
/**
 * 计算帖子的热门分数
 *
 * calculateTopicHotScore.class.php
 * Created by IntelliJ IDEA.
 *
 * @author: hjh <hjh@jf.com>
 *
 * Date: 2017/10/28
 * Time: 11:06
 */

require_once dirname(__DIR__) . "/cronBase.php";

use Common\Bridge;
use Recommend\HotRank;

class calculateTopicHotScore extends cronBase
{
    public function doDefault()
    {
        $maxCount = 0;

        global $argv;
        if (count($argv) > 1) {
            $maxCount = intval($argv[1]);
        }

        // 便利所有的文章，计算score，更新es
        $pdo = Bridge::pdo(Bridge::DB_CIRCLE_R);
        $pageCount = 200;
        $offset = 0;
        $table = 'Topic';

        $countData = $pdo->select("count('TopicId') as num")->from($table)->getOne();
        if (empty($countData)) {
            debug_log('calculateTopicHotScore failed, get Topic count failed', JF_LOG_ERROR);
            return;
        }
        $count = $maxCount > 0 ? min($countData['num'], $maxCount) : $countData['num'];

        while ($offset < $count) {

            $list = $pdo->select('TopicId,ViewCount,LikeCount,CommentCount,ShareCount,DislikeCount,CreateTime')->from($table)->order('TopicId DESC')->limit($offset,
                min($pageCount, $count - $offset))->getAll();

            if (empty($list)) {
                debug_log("calculateTopicHotScore error, offset: {$offset}, count: {$count}", JF_LOG_ERROR);
                break;
            }

            foreach ($list as $v) {
                $hotScore = HotRank::score($v['ViewCount'], $v['LikeCount'], $v['DisLikeCount'], $v['ShareCount'],
                    $v['CommentCount'], $v['CreateTime']);

                $this->updateEs($v['TopicId'], $hotScore);

                debug_log("calculateTopicHotScore, TopicId: {$v['TopicId']},  hotScore: {$hotScore}");

                usleep(50 * 1000);
            }

            $offset += $pageCount;

            usleep(200 * 1000);
        };
    }

    private function updateEs($topicId, $hotScore)
    {
        $query = \Search\SearchTopic::TOPIC_SEARCH . $topicId . '/_update';

        $es = Bridge::search();

        $ret = $es->query($query, 'POST', [
            'doc' => [
                \Search\SearchTopic::FIELD_HOT_SCORE => $hotScore
            ]
        ]);
        if ($ret === false) {
            debug_log('calculateArticleHotScore updateEs failed, topicId:' . $topicId . ' score:' . $hotScore, ' error:' . json_encode($ret, JSON_UNESCAPED_UNICODE));
        }
    }
}

$app->run();
